package com.yj.core.helper;

import com.yj.core.exception.ServiceException;
import com.yj.core.result.BaseExceptionMsg;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redis操作工具类
 * Key生成说明
 * 1)公共数据，微服务之前共享数据（比如字典、科室等）
 * key=公共数据标识:数据标识（业务表主键｜自定义Key）
 * 2)微服务业务数据
 * key=微服务标识:数据标识（业务表主键｜自定义Key）
 * <p>
 * 数据标识必须唯一
 *
 * @author yxp
 * @date 19-3-16
 */
@Slf4j
@Component
public class RedisHelper {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    /**
     * 判断缓存是否存在
     *
     * @param cacheName
     * @param key
     * @return
     */
    public Boolean existKey(String cacheName, String key) {
        if (StringUtils.isAnyBlank(cacheName, key)) {
            throw new ServiceException(BaseExceptionMsg.PARAM_INVALID);
        }
        return redisTemplate.hasKey(redisKey(cacheName, key).toLowerCase());
    }

    /**
     * 保存
     *
     * @param cacheName
     * @param key
     * @param t
     * @param <T>
     */
    public <T> void setObj(String cacheName, String key, T t) {
        if (t == null || StringUtils.isAnyBlank(cacheName, key)) {
            throw new ServiceException(BaseExceptionMsg.PARAM_INVALID);
        }
        BoundValueOperations<String, T> valueOperations = redisTemplate.boundValueOps(redisKey(cacheName, key).toLowerCase());
        valueOperations.set(t);
    }

    /**
     * 保存
     *
     * @param cacheName
     * @param key
     * @param t
     * @param <T>
     */
    public <T> void setObj(String cacheName, String key, List<T> t) {
        if (t == null || StringUtils.isAnyBlank(cacheName, key)) {
            throw new ServiceException(BaseExceptionMsg.PARAM_INVALID);
        }
        BoundValueOperations<String, List<T>> valueOperations = redisTemplate.boundValueOps(redisKey(cacheName, key).toLowerCase());
        valueOperations.set(t);
    }

    /**
     * 保存
     *
     * @param cacheName
     * @param key
     * @param t
     * @param timeout
     * @param <T>
     */
    public <T> void setObj(String cacheName, String key, T t, long timeout) {
        if (t == null || StringUtils.isAnyBlank(cacheName, key)) {
            throw new ServiceException(BaseExceptionMsg.PARAM_INVALID);
        }
        BoundValueOperations<String, T> valueOperations = redisTemplate.boundValueOps(redisKey(cacheName, key).toLowerCase());
        valueOperations.set(t, timeout, TimeUnit.SECONDS);
    }

    /**
     * 保存
     *
     * @param cacheName
     * @param key
     * @param t
     * @param timeout
     * @param <T>
     */
    public <T> void setObj(String cacheName, String key, List<T> t, long timeout) {
        if (t == null || StringUtils.isAnyBlank(cacheName, key)) {
            throw new ServiceException(BaseExceptionMsg.PARAM_INVALID);
        }
        BoundValueOperations<String, List<T>> valueOperations = redisTemplate.boundValueOps(redisKey(cacheName, key).toLowerCase());
        valueOperations.set(t, timeout, TimeUnit.SECONDS);
    }

    /**
     * 获取缓存对象
     *
     * @param cacheName
     * @param key
     * @param tClass
     * @param <T>
     * @return
     */
    public <T> T getObj(String cacheName, String key, Class<T> tClass) {
        if (StringUtils.isAnyBlank(cacheName, key)) {
            throw new ServiceException(BaseExceptionMsg.PARAM_INVALID);
        }
        String redisKey = redisKey(cacheName, key).toLowerCase();

        boolean hasKey = redisTemplate.hasKey(redisKey);
        if (!hasKey) {
            log.error("redis key={} 不存在", key);
            return null;
        }
        BoundValueOperations<String, T> valueOperations = redisTemplate.boundValueOps(redisKey);
        if (tClass == String.class) {
            return valueOperations.get();
        }
        return JSON.parseObject(valueOperations.get().toString(), tClass);
    }

    /**
     * 获取缓存对象
     *
     * @param cacheName
     * @param key
     * @param tClass
     * @param <T>
     * @return
     */
    public <T> List<T> getArrayObj(String cacheName, String key, Class<T> tClass) {
        if (StringUtils.isAnyBlank(cacheName, key)) {
            throw new ServiceException(BaseExceptionMsg.PARAM_INVALID);
        }
        String redisKey = redisKey(cacheName, key).toLowerCase();

        boolean hasKey = redisTemplate.hasKey(redisKey);
        if (!hasKey) {
            log.error("redis key={} 不存在", key);
            return null;
        }
        BoundValueOperations<String, List<T>> valueOperations = redisTemplate.boundValueOps(redisKey);

        return JSONArray.parseArray(valueOperations.get().toString(), tClass);
    }

    /**
     * 清空公共的缓存
     *
     * @param cacheName
     * @param redisKey
     */
    public void delRedis(String cacheName, String redisKey) {
        Set<String> keys = stringRedisTemplate.keys(redisKey(cacheName, redisKey).toLowerCase() + "*");
        redisTemplate.delete(keys);
    }


    /**
     * 自增
     *
     * @param key
     * @param liveTime
     * @return
     */
    public Long incr(String cacheName,String key, long liveTime) {
        String redisKey = redisKey(cacheName, key).toLowerCase();
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(redisKey, redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.getAndIncrement();

        boolean in = increment == null || increment.longValue() == 0;
        if (in && liveTime > 0) {
            entityIdCounter.expire(liveTime, TimeUnit.SECONDS);
        }
        return increment;
    }


    /**
     * 生成缓存Key
     *
     * @param cacheName
     * @param redisKey
     * @return
     */
    private String redisKey(String cacheName, String redisKey) {
        return cacheName + "::" + redisKey;
    }
}
